﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace PubSubGeneric
{
    public class SubscriptionService : ISubscriptionService
    {
        public ISubscriptionCatalog SubscriptionCatalog
        {
            get;
            set;
        }

        public SubscriptionService()
            : this(PubSubManager.Catalog)
        {

        }

        public SubscriptionService(ISubscriptionCatalog subscriptionCatalog)
        {
            this.SubscriptionCatalog = subscriptionCatalog;
        }

        public void Subscribe<T>(string topic, ISubscriber<T> subscriber)
        {
            Subscribe<T>(topic, subscriber, null);
        }

        public void Subscribe<T>(string topic, ISubscriber<T> subscriber, Expression<Func<T, bool>> predicate)
        {
            Trace.WriteLine("Subscribing in " + topic + " with expression " + (predicate == null ? " all " : predicate.ToString()));
            SubscriptionCatalog.Add(topic, new SubscriptionInfo<T>(subscriber, predicate));
        }

        public void UnSubscribe<T>(string topic, ISubscriber<T> subscriber)
        {
            UnSubscribe<T>(topic, subscriber, null);
        }

        public void UnSubscribe<T>(string topic, ISubscriber<T> subscriber, Expression<Func<T, bool>> predicate)
        {
            Trace.WriteLine("UnSubscribing from " + topic + " with expression " + (predicate == null ? " all " : predicate.ToString()));
            this.SubscriptionCatalog.Remove(topic, new SubscriptionInfo<T>(subscriber, predicate));
        }
    }
}
